//
//  RoomShowViewController.m
//  LiveEducation
//
//  Created by Liu,Qingcan on 2017/4/16.
//  Copyright © 2017年 Baidu. All rights reserved.
//

#import "RoomCategoryController.h"
#import "UIScrollView+MJRefresh.h"
#import "RoomCategoryViewCell.h"
#import "RoomCategoryViewLayout.h"
#import "MJRefresh.h"
#import "UIView+WLExtension.h"
#import "RoomDetailViewController.h"
#import "RoomModel.h"
#import "RoomInfoApi.h"
#import "RoomDefalutApi.h"
#import "MBProgressHUD.h"
#import "LERoomItem.h"

#import "YYWebImage.h"
#import "LiveViewController.h"

static  NSString * reusedddIdetifier = @"roomCell";

static BOOL databaseHasData = NO;



@interface RoomCategoryController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic,strong)UILabel *label;
@property (nonatomic,strong)NSString *categoryName;
@property (nonatomic,assign)NSInteger categoryId;
@property (nonatomic,assign)NSInteger currentPageNumber;


@property (nonatomic,strong)UICollectionView *myCollectionView;
@property (nonatomic,strong)RoomCategoryViewCell *roomCollectionCell;
@property (nonatomic,strong)RoomCategoryViewLayout *roomLayout;

@property (nonatomic,strong)RoomDetailViewController *roomDetailVC;

@property (nonatomic, strong) NSMutableArray *roomList;


//添加刷新头 和尾
@property (nonatomic,strong)MJRefreshBackNormalFooter *mj_footer;
@property (nonatomic,strong)MJRefreshStateHeader *mj_header;


@property (nonatomic,assign)CGRect viewFrame;
@property (nonatomic,strong)NSMutableArray *cellArray;

@end

@implementation RoomCategoryController

+ (instancetype)initWithCategoryName:(NSString *)name categoryId:(NSInteger)cateId frame:(CGRect)frame{
    return [[self alloc] initWithCategoryName:name categoryId:cateId frame:(CGRect)frame];
}

- (instancetype)initWithCategoryName:(NSString *)name categoryId:(NSInteger)cateId frame:(CGRect)frame{
    self = [super init];
    if (self) {
//        self.view.frame = frame;
//        self.myCollectionView.frame = frame;
        self.categoryName = name;
        self.viewFrame = frame;
        self.categoryId = cateId;
        self.currentPageNumber = 0;
        
    }
    return self;
}


//- (void)loadView{
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupViews];
//    [self headerDidPull];
    [self.myCollectionView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [self.myCollectionView reloadData];
    
}

#pragma mjrefresh delegate




#pragma delegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"lll %ld",(long)indexPath.row);
//    RoomCategoryItem *item = [self.roomList objectAtIndex:indexPath.row];
    LERoomItem *item = [self.roomList objectAtIndex:indexPath.row];
    
    RoomDetailViewController *detailVC = [[RoomDetailViewController alloc]init];
    detailVC.roomItem = item;
    if ([item.price hasPrefix:@"rtmp"]) {
        LiveViewController *watchVC = [LiveViewController initWithLiveUrl:item.price];
        watchVC.title = @"直播画面";
        watchVC.view.backgroundColor = [UIColor whiteColor];
        [self.navigationController pushViewController:watchVC animated:YES];
    }else{
        [self.navigationController pushViewController:detailVC animated:YES];
    }
    
}

#pragma mark datasource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.roomList.count;
}

- ( UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
//    [_myCollectionView registerClass:[RoomCategoryViewCell class] forCellWithReuseIdentifier:@"cellsss"];
//    [self.myCollectionView reloadData];
    RoomCategoryViewCell *cell = [_myCollectionView dequeueReusableCellWithReuseIdentifier:reusedddIdetifier forIndexPath:indexPath];
    
     [cell setupCellDatas:self.roomList[indexPath.row]]; //新赋值 /// 暂时没使用
//    if (cell.roomItem==nil) {
//        cell =  [RoomCategoryViewCell initRoomCollectionCellWithRoomItem:self.roomList[indexPath.row]];
//    }
    
//    if(cell.roomItem!=nil){
//        [self.cellArray addObject:indexPath]; //重用
//    }else{
//        [cell setupCellDatas:self.roomList[indexPath.row]]; //新赋值 /// 暂时没使用
//    }
    
    
////    if (_roomCollectionCell) {
//        _roomCollectionCell =  [RoomCategoryViewCell initRoomCollectionCellWithRoomItem:self.roomList[indexPath.row]];
////    }
    
    return cell;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}


//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//    return CGSizeMake(140, 100);
//}

//- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
//    return self.roomList.count;
//}


//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
//    if (kind == UICollectionElementKindSectionFooter) {
//        return  self.mj_footer;
//    }
//}



#pragma mark event response
- (void)headerDidPull{
    [self.mj_footer endRefreshing];
    
    [self.mj_header beginRefreshing];
    
    [self loadPullDatas];
//    [self.myCollectionView reloadData];
}


- (void)footerDidPush{
    [self.mj_header endRefreshing];
    [self.mj_footer beginRefreshing];
    
    
    
    
    [self loadPushDatas];
    
}


#pragma private

- (void)loadPullDatas{
    ///1.判断static 是否为true,
    ///false -- 去数据库是否有数据
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"从服务器获得更多数据中 。。。";
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    hud.backgroundColor = [UIColor lightGrayColor];
    
    
    RoomModel *roomModel = [[RoomModel alloc]init];
    
    
    NSArray *arr = [roomModel selectRoomsByCeteId:self.categoryId];
    if (arr.count > 0) {
        databaseHasData = YES;
    }else{
        databaseHasData = NO;
    }
    
    self.roomList = [NSMutableArray array];
    self.currentPageNumber = 0;
    if (databaseHasData) { //有数据
//        NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
//        BOOL isPushNewRoom = [def boolForKey:@"user_add_new_room"];
//        if (isPushNewRoom) {
            [roomModel deleteAllRoom];
            [self requestForNoData:hud];
//        }else{
//            [self.roomList addObjectsFromArray: [roomModel selectNumberOfData:self.currentPageNumber * 10 cateId:self.categoryId]];
//            self.currentPageNumber ++;
//            [self.myCollectionView reloadData];
//            [self.mj_footer endRefreshing];
//            [self.mj_header endRefreshing];
//            [hud hideAnimated:YES afterDelay:0.5f];
//        }
    }else{ //无数据
        
        [self requestForNoData:hud];
    }
    
    
    self.roomLayout.columnCount = 2;
    self.roomLayout.roomArray = self.roomList;
    
}


- (void)loadPushDatas{

//    for (UIView *views in self.myCollectionView.subviews) {
//        if (![views isKindOfClass:[MJRefreshHeader class]]){
//            [views removeFromSuperview];
//        }
//    }
//    [self.myCollectionView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.backgroundColor = [UIColor lightGrayColor];
    hud.label.text = @"正在加载数据，请稍候";
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    
    ///1.根据当前pagenumber,判断数据库是否还有数据
    RoomModel *roomDB = [[RoomModel alloc]init];
    NSArray *roomArr = [roomDB selectNumberOfData:self.currentPageNumber*10 cateId:self.categoryId];
    if (roomArr.count > 0) {//数据够///3.有数据，直接拿来展示；
        [self.roomList addObjectsFromArray:roomArr];
        self.currentPageNumber ++;
        [self.myCollectionView reloadData];
        [self.mj_footer endRefreshing];
        [hud hideAnimated:YES afterDelay:0.5f];
    }else{///2.无数据，则请求10条数据存数据库
        RoomInfoApi *infoApi = [[RoomInfoApi alloc]initWithCategoryId:self.categoryId pageNumber:self.currentPageNumber hopeNumber:10];
        [infoApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            NSDictionary *dict = request.responseJSONObject;
            //2.判断服务器状态码
            NSArray *categories = [NSArray array];
            NSNumber *status = [dict objectForKey:@"statusCode"];
            
            if (status.integerValue == 1) {
                categories = dict[@"data"];
//                [self.roomList addObjectsFromArray:categories];
                //                [self.myCollectionView reloadData];
                
                //3.success,存数据库
                for(NSDictionary *dc in categories){
                    LERoomItem *room = [LERoomItem yy_modelWithJSON:dc];
                    [roomDB insertRoomData:room];
                    [self.roomList addObject:room];
                    
                }
                self.currentPageNumber ++;
                NSLog(@"请求 room 10 条信息 -- 成功");
                
                if(categories.count == 0){
                    [self.mj_footer endRefreshingWithNoMoreData];
                }
                    
            }else{
                //2.输出状态码
                NSLog(@"未能成功获得数据 the reason is : %@",dict[@"statusMsg"]);
                [self.mj_footer endRefreshingWithNoMoreData];
            }
            [hud hideAnimated:YES afterDelay:0.5f];
            [self.mj_footer endRefreshing];
            [self.myCollectionView reloadData];
            
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            NSLog(@"网络请求 room 10 条信息失败");
            
            NSError *error = nil;
            [NSException raise:@"网络请求 room 10 条信息失败" format:@"%@",[error localizedDescription]];
            [hud hideAnimated:YES afterDelay:.5f];
        }];

    }
    
//    [self.myCollectionView reloadInputViews];
}



- (void)requestForNoData:(MBProgressHUD *)hud{
    RoomModel *roomModel = [[RoomModel alloc]init];
    RoomDefalutApi *api = [[RoomDefalutApi alloc]initWithCategoryId:self.categoryId];
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSDictionary *dict = request.responseJSONObject;
        //2.判断服务器状态码
        NSArray *categories = [NSArray array];
        NSNumber *status = [dict objectForKey:@"statusCode"];
        
        if (status.integerValue == 1) {
            categories = dict[@"data"];
            if (categories.count > 0) {
                //3.success,存数据库
                for(NSDictionary *dc in categories){
                    LERoomItem *room = [LERoomItem yy_modelWithJSON:dc];
                    [roomModel insertRoomData:room];
                    [self.roomList addObject:room];
                }
                self.currentPageNumber ++;
                NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
                [def setBool:NO forKey:@"user_add_new_room"];

                NSLog(@"请求 room 10 条信息 -- 成功");
            }else{
                [self.mj_footer endRefreshingWithNoMoreData];
                
                
                [self.mj_header setTitle:@"服务器无更多数据了" forState:MJRefreshStateIdle];
                UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(self.view.bounds.size.width /2.f - 150, self.myCollectionView.frame.size.height/2.f - 20, 300, 40)];
                label.text = @"QAQ 服务器无更多数据了 QAQ";
                label.textAlignment = NSTextAlignmentCenter;
                [self.myCollectionView addSubview:label];
                
            }
            
        }else{
            //2.输出状态码
            NSLog(@"未能成功获得数据 the reason is : %@",dict[@"statusMsg"]);
        }
        [hud hideAnimated:YES afterDelay:0.5f];
        [self.mj_header endRefreshing];
        [self.myCollectionView reloadData];
        
        
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"网络请求 room 10 条信息失败");
        
        NSError *error = nil;
        //            [NSException raise:@"网络请求 room 10 条信息失败" format:@"%@",[error localizedDescription]];
        [hud hideAnimated:YES afterDelay:.5f];
        [self.mj_header endRefreshing];
        
    }];
    

}



- (void)setupViews{
    self.label.text = _categoryName;
    self.view.frame = _viewFrame;
    
    [self.view addSubview:self.myCollectionView];
//    [self.view addSubview:self.label];
}


#pragma mark getter

- (UILabel *)label {
    if (!_label) {
        _label = [[UILabel alloc]initWithFrame:CGRectMake(100, 200, 200, 100)];
        _label.backgroundColor = [UIColor lightGrayColor];
    }
    return _label;
    
}


- (UICollectionView *)myCollectionView{
    if (!_myCollectionView) {
         self.roomLayout = [[RoomCategoryViewLayout alloc]init];
//        NSLog(@"kkkkkk %f",self.navigationController.tabBarController.tabBar.bounds.size.height);
        _myCollectionView = [[UICollectionView alloc]initWithFrame:_viewFrame collectionViewLayout:_roomLayout];
        
        _myCollectionView.backgroundColor = [UIColor colorWithRed:206/255.f green:206/255.f blue:206/255.f alpha:0.8f];
        _myCollectionView.showsHorizontalScrollIndicator = NO;
        _myCollectionView.showsVerticalScrollIndicator = YES;
        
        //设置下内边距
        _myCollectionView.mj_insetB = 30;//== _myCollectionView.contentInset.bottom
        
        
        /// 如果是从纯代码加载，则用下列方式注册
        [_myCollectionView registerClass:[RoomCategoryViewCell class] forCellWithReuseIdentifier:reusedddIdetifier];
        /// 如果是storyboard或者xib加载，则用下列方式注册
//        [_myCollectionView registerNib:[UINib nibWithNibName:@"RoomCategoryViewCell" bundle:nil] forCellWithReuseIdentifier:reusedddIdetifier];

        
        
        //添加header
        _myCollectionView.mj_header = self.mj_header;
        //添加footer
        _myCollectionView.mj_footer = self.mj_footer;
        
        
        //添加delegate
        _myCollectionView.delegate = self;
        _myCollectionView.dataSource = self;

    }
    return _myCollectionView;
}

- (NSMutableArray *)roomList{
    if (!_roomList) {
        _roomList = [NSMutableArray array];
        
//        for (int i = 0; i < 10; i++) {
//            RoomCategoryItem *item = [[RoomCategoryItem alloc]init];
//            item.roomName = [NSString stringWithFormat:@"中公教育课程 -- %d",i];
//            NSDate *d = [NSDate date];
//            NSTimeInterval time = [d timeIntervalSinceReferenceDate];
//            NSDate *date = [[NSDate alloc]initWithTimeIntervalSinceNow:time];
//            NSDateFormatter *format = [[NSDateFormatter alloc]init];
//            [format setDateFormat:@"yyyy-MM-dd HH:mm"];
//            item.roomDate = [format stringFromDate:date];
//            
//            item.price = @"免费";
//            item.roomImage = @"backImage";
//            [_roomList addObject:item];
//        }
        
    }
    return  _roomList;
}


- (MJRefreshStateHeader *)mj_header{
    if (!_mj_header) {
        _mj_header = [MJRefreshStateHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerDidPull)];
        _mj_header.backgroundColor = [UIColor clearColor];
//        [_mj_header setTitle:@"即将刷新" forState:MJRefreshStateWillRefresh];
        [_mj_header setTitle:@"刷新ing ..." forState:MJRefreshStateRefreshing];
//        [_mj_header setTitle:@"刷新完成" forState:mjrefrestate]
        
        _mj_header.automaticallyChangeAlpha = YES;
        void (^endRefresh)(void) = ^(void){
//            [self.myCollectionView reloadItemsAtIndexPaths:self.cellArray];
        };
        [_mj_header setEndRefreshingCompletionBlock:endRefresh];
    }
    return _mj_header;
}


- (MJRefreshBackNormalFooter *)mj_footer{
    if (!_mj_footer) {
        _mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerDidPush)];
        _mj_footer.automaticallyChangeAlpha = YES;
        _mj_footer.automaticallyHidden = YES;
        
        _mj_footer.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
        [_mj_footer setTitle:@"松开将加载更多数据" forState:MJRefreshStatePulling];
        
        _mj_footer.backgroundColor = [UIColor clearColor];
    }
    return _mj_footer;
}

- (RoomDetailViewController *)roomDetailVC{
    if (!_roomDetailVC) {
        _roomDetailVC = [[RoomDetailViewController alloc]init];
        
    }
    return _roomDetailVC;
}

- (NSMutableArray *)cellArray{
    if (!_cellArray) {
        _cellArray = [NSMutableArray array];
    }
    return _cellArray;
}
@end
